var ws;
var tryonce = false;
var connected = false;
var server_addr = "ws://127.0.0.1:18888";//本机端口地址
var iswaiting = false;
const CLT_MSG = {
    // 打开相机 cap:相机ID
    BEGIN_CAP: 1,
    // 关闭相机 cap:相机ID
    STOP_CAP: 2,
    // 获取PID
    GET_PID: 3,
    // 获取分辨率
    GET_FBL: 4,
    //设置分辨率
    SET_FBL: 5,
    //设置MJPG格式
    SET_MJPG: 6,
    //设置视频旋转
    SET_TURN: 7,
    //设置视频截图保存的jpg质量
    SET_QUALITY: 8,
    //设置自动裁边
    SET_AUTOCROP: 9,
    //设置预设框选
    SET_PREST: 10,
    //获取当前预设框选
    GET_PREST_INFO: 11,
    //视频格式弹窗
    FORMAT_DLG: 12,
    //视频属性弹窗
    PROPERTY_DLG: 13,
    //设置截图颜色模式 彩色 黑白 灰度
    SET_COLOR_MODEL: 14,
    //截图
    GET_PICTURE: 15,
    //设置去底色参数
    SET_CLEAN_PARAM: 16,
    //内存截图
    GET_PICTURE_MEM: 17,
    //base64测试
    TEST_BASE64: 18,
    //制作PDF的临时目录
    SET_TEMPDIR: 19,
    //开始制作PDF
    BEGIN_PDF: 20,
    //PDF截图 保存到PDF临时目录
    GET_PDF_PICTURES: 21,
    //结束制作PDF
    END_PDF_PICTURES: 22,
    //PDF文件转为文件里的BASE64码
    PDF_TO_BASE64: 23,
    //文件里的BASE64码转为PDF文件
    BASE64_TO_PDF: 24,
    //PDF文件转为BASE64字符串
    PDF_TO_BASE64_STR: 25,
    //删除制作PDF的图片文件
    DEL_PICTURE_PDF: 26,
    //打印图片
    PRINT_IMAGE: 27,
    //设置显示错误弹窗
    SHOW_ERROR_BOX: 28,
    //获取视频连接事件
    GET_EVENT: 29,
    //预设框选鼠标消息
    PRESET_MOUSEDOWN: 30,
    PRESET_MOUSEMOVE: 31,
    PRESET_MOUSEUP: 32,

    //多图裁剪
    MULTI_DETE: 33,
    //人脸检测
    FACE_DETE: 34,
    //设置DPI
    SET_DPI: 35,
    //版本信息
    LIB_INFO: 36,

    IDCARD_COPY: 37,
    CANCEL_IDCARD_COPY: 38,

    //人证对比
    FI_INIT: 41,
    IDCARD_COMPARE: 40,
    FI_UNIT: 42,

    BEGIN_RECORD_VIDEO: 43,
    STOP_RECORD_VIDEO: 44,
    PAUSE_RECORD_VIDEO: 45,
    RESUME_RECORD_VIDEO: 39,

    BASE64_COMPARE: 46,
    DETECT_FACE: 47,
    STOP_DETECT_FACE: 48,
    GET_DEVICE_SERIAL: 49,
    GET_FLASH_SERIAL: 50,

    SET_AUTOOFFSET: 111,

    //http上传下载
    HTTP_UPLOAD: 120,
    HTTP_DOWNLOAD: 121,
    HTTP_GETPROGRESS: 122,
    HTTP_GETRESULT: 123,
    HTTP_CLOSE: 124,

    SET_OPEN_AUDIO: 151,
    SET_RECORD_AUDIO: 152,
};

export const creatWS = () => {    
    if(ws != null) return;
    ws = new WebSocket(server_addr);    
    ws.onopen = function (evt) {
        if (connected) { return; }

        connected = true;
        console.log("已经连接到服务器");
        cam_switch()
    };

    ws.onclose = function (evt) {
        ws = null;        
        if (connected) {
            console.log("已断开服务器连接");
            connected = false;
            tryonce = false;
        }
        
    }

    ws.onmessage = function (evt) {
        if (evt.data.length === 0) {
            return;
        }
        if (typeof evt.data === 'string') {
            var msg = JSON.parse(evt.data);
            if (msg.err && msg.err !== 0) {
                console.log("错误 - " + msg.err + ", " + msg.msg);
            }
            else if (msg.msg) {
                console.log(msg.msg);
            }

            if (msg.user_data) {
                callback[msg.user_data](msg);
                if (typeof msg.user_data === 'number') {
                    callback[msg.user_data] = undefined;
                }
            }
        }
    }
    ws.onerror = function(evt){
        
    }
    return ws
}

var context = 1;
var callback = {}

export const sendMsg = (proto, msg, cb) => { //向后台发送消息的处理函数

    if (!ws) {
        return;
    }    
    if(ws.readyState!=1){
        return
    }
    if (typeof msg !== 'object') {
        if (typeof msg === 'function') {
            cb = msg;
            msg = {};
        }
        else {
            msg = {}
        }
    }

    msg.proto = proto;
    if (typeof cb === 'function') {
        callback[++context] = cb;
        msg.user_data = context;
    }

    ws.send(JSON.stringify(msg));
}

const cam_switch = () =>  //打开视频
{

    if (!connected) {
        console.log("flshell未启动，请稍等片刻或手动启动C:\\高拍仪html\\flshell.exe");
        return;
    }

    if (iswaiting) return;
    iswaiting = true;
    sendMsg(CLT_MSG.BEGIN_CAP, { cap: 1 }, function (msg) {
        if (msg.err !== 0) {
            iswaiting = false;
            console.log("打开视频失败");
        }

        console.log("打开视频1" + "成功，width = " + msg.width + ",height =  " + msg.height);
        iswaiting = false;
    });
}

export const closeCap = () =>  //打开视频
{
    sendMsg(CLT_MSG.STOP_CAP, function(msg){
        if(msg.err !== 0){ 
            iswaiting = false;
            console.log("关闭视频失败");}    
        console.log("关闭视频成功");        
        iswaiting = false;  
        ws.onclose()
        
    }); 
    
}




export const getcar = () => {
    iswaiting = false;
    upprocess = 0;
    uploadId = 0;
    var capID = 1
    if (!connected) {
        console.log("flshell未启动，请稍等片刻或手动启动C:\\高拍仪html\\flshell.exe");
        return;
    }
    //sendMsg(CLT_MSG.SET_COLOR_MODEL,{color:0});// 0\ 1\ 2   //设置颜色模式 只针对截图
    if (iswaiting) return;
    iswaiting = true;

    sendMsg(CLT_MSG.BEGIN_CAP, { cap: capID }, function (msg) {
        if (msg.err !== 0) {
            iswaiting = false;
            console.log("打开视频失败");
            return
        }
        console.log("打开视频" + capID + "成功");
        
        sendMsg(CLT_MSG.GET_EVENT, function (msg) {
            if (msg.err !== 0) {
                iswaiting = false;
                return;
            }
    
            var event = msg.event;
            switch (event) {
                case 2:
                    console.log("设备连接中断，请重新连接后再次打开视频。");
                    break;
    
                case 1:
                    console.log("初始化成功");
                    break;
    
                case 0:
                    console.log("设备非法");
                    break;
            }
            
            sendMsg(CLT_MSG.GET_PICTURE, { path: "D:\\tmp\\111.jpg", turn: 0 }, function (msg) {   //截图
                if (msg.err !== 0) {
                    iswaiting = false;
                    console.log("截图失败")
                    return;
                }
                console.log("截图完成")
    
                sendMsg(CLT_MSG.HTTP_UPLOAD, { url: "https://www.chuandaolundu.com/api/v2/scene/ocr/recognize_car", filepath: "D:\\tmp\\111.jpg" }, function (msg) {
                    if (msg.err !== 0) {
                        iswaiting = false;
                        console.log("上传失败")
                        return;
                    }
                    uploadId = msg.idtask;
    
                    //获取上传结果
                    var error;
                    sendMsg(CLT_MSG.HTTP_GETRESULT, { idtask: uploadId }, function (msg) {
                        if (msg.err !== 0) return;
                        error = msg.error;
                        if (error == "") {
                            start_progresstimer();
                        }
    
                    });
    
                });
            });
    
        });

    });

    


    
};


export const getidcard = () => {
    iswaiting = false;
    upprocess = 0;
    uploadId = 0;
    var capID = 1
    if (!connected) {
        console.log("flshell未启动，请稍等片刻或手动启动C:\\高拍仪html\\flshell.exe");
        return;
    }
    //sendMsg(CLT_MSG.SET_COLOR_MODEL,{color:0});// 0\ 1\ 2   //设置颜色模式 只针对截图
    if (iswaiting) return;
    iswaiting = true;

    sendMsg(CLT_MSG.BEGIN_CAP, { cap: capID }, function (msg) {
        if (msg.err !== 0) {
            iswaiting = false;
            console.log("打开视频失败");
            return
        }
        console.log("打开视频" + capID + "成功");
       
        sendMsg(CLT_MSG.GET_EVENT, function (msg) {
            if (msg.err !== 0) {
                iswaiting = false;
                return;
            }
    
            var event = msg.event;
            switch (event) {
                case 2:
                    console.log("设备连接中断，请重新连接后再次打开视频。");
                    break;
    
                case 1:
                    console.log("初始化成功");
                    break;
    
                case 0:
                    console.log("设备非法");
                    break;
            }
            
            sendMsg(CLT_MSG.GET_PICTURE, { path: "D:\\tmp\\111.jpg", turn: 0 }, function (msg) {   //截图
                if (msg.err !== 0) {
                    iswaiting = false;
                    console.log("截图失败")
                    return;
                }
                console.log("截图完成")
    
                sendMsg(CLT_MSG.HTTP_UPLOAD, { url: "https://www.chuandaolundu.com/api/v2/scene/ocr/recognize_idcard", filepath: "D:\\tmp\\111.jpg" }, function (msg) {
                    if (msg.err !== 0) {
                        iswaiting = false;
                        console.log("上传失败")
                        return;
                    }
                    uploadId = msg.idtask;
    
                    //获取上传结果
                    var error;
                    sendMsg(CLT_MSG.HTTP_GETRESULT, { idtask: uploadId }, function (msg) {
                        if (msg.err !== 0) return;
                        error = msg.error;
                        if (error == "") {
                            start_progresstimer();
                        }
    
                    });
    
                });
            });
    
        });

    });

    


    
};

export const getUploadData = () => {
    return uploadResult
}

export const clearUploadData = () => {
    uploadResult=""
}

var uploadId = 0;
var upprocess = 0;
var isupload = true
var uploadResult = ""
function start_progresstimer() {
    uploadResult = ""
    setTimeout(() => {
        update_progress()
    }, 500);

}

function update_progress() {
    sendMsg(CLT_MSG.HTTP_GETPROGRESS, { idtask: uploadId }, function (msg) {
        if (msg.err !== 0) return;
        upprocess = msg.process;
    });

    if (upprocess <= 0)
        upprocess = 0;
    if (upprocess == 100) {
        var result;
        sendMsg(CLT_MSG.HTTP_GETRESULT, { idtask: uploadId }, function (msg) {
            if (msg.err !== 0) return;
            result = msg.error;
            uploadResult = result
            console.log("上传完成")
            sendMsg(CLT_MSG.HTTP_CLOSE, { idtask: uploadId }, function (msg) {
                if (msg.err !== 0) return;
                console.log("上传线程已关闭");

            });
        });
        iswaiting = false;
        upprocess = 0;
        uploadId = 0;       
        return
    }
    setTimeout(() => {
        update_progress()
    }, 500);
}
